package com.jly.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jly.service.RedisService;
import com.jly.service.RedisService4;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class util {

    public static String getToken(RedisService redisService){
        if(redisService.existskey("access_token")){
            return redisService.getStringValue("access_token");
        }else{
            String param = "grant_type=client_credential&appid="+Constants.APPID+"&secret="+Constants.APPSECRET;
            String results = HttpPOSTUtil.sendPost(Constants.getTokenUrl,param);
            JSONObject json = JSON.parseObject(results);
            redisService.setString("access_token",json.getString("access_token"),7200L);
            return json.getString("access_token");
        }
    }

    public static String getOpenid(String code) throws Exception{
        String param = "appid="+Constants.APPID;
        param += "&secret="+Constants.APPSECRET;
        param += "&code="+code;
        param += "&grant_type=authorization_code";
        String result = HttpPOSTUtil.sendGet(Constants.getAuthTokenUrl,param);
        JSONObject json = JSON.parseObject(result);
        if(!json.containsKey("openid")){
            throw new Exception("not found openid");
        }
        return json.getString("openid");
    }

    /**
     * 判断是否为空字符串(文本类工具)
     *
     * @param value
     * @return 空为true，否则false
     */
    public static boolean isEmpty(String value) {
        int strLen;
        if (value == null || (strLen = value.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(value.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    public static JSONObject sendPost(String url,JSONObject json) throws  Exception{
        String sign = SignUtil.generateSignature(json);
        json.put("sign", sign);
        return JSON.parseObject(HttpPOSTUtil.sendPost(url, "id=" + json.toJSONString()));
    }
    /**
     * 生成N位随机数
     *
     * @param n
     * @return
     */
    public static long generateRandomNumber(int n) {
        if (n < 1) {
            throw new IllegalArgumentException("随机数位数必须大于0");
        }
        return (long) (Math.random() * 9 * Math.pow(10, n - 1)) + (long) Math.pow(10, n - 1);
    }

    /**
     * 微信推送模板消息
     * @throws Exception
     */
    public static JSONObject pushMessage(JSONObject jsonobj,String [] arr,String [] arr2,RedisService4 redisService4) throws Exception{
        JSONObject data = new JSONObject();
        data.put("touser", jsonobj.getString("openid"));
        data.put("template_id", jsonobj.getString("TemplateId"));
        data.put("appid", Constants.APPID);
        if (!util.isEmpty(jsonobj.getString("url"))){
            data.put("url", jsonobj.getString("url"));
        }
        JSONObject jsons = new JSONObject();
        for (int i = 0; i < arr.length; i++) {
            JSONObject json = new JSONObject();
            json.put("value", arr2[i]);
            json.put("color", "#4169E1");
            jsons.put(arr[i], json);
        }
        data.put("data", jsons);
        String results = HttpPOSTUtil.sendPost(Constants.SEND_PushAuthCodeUrl + "?access_token=" + jsonobj.getString("access_token"), data.toJSONString());
        JSONObject json = JSON.parseObject(results);
        JSONObject result = new JSONObject();
        if(0 == json.getInteger("errcode")){
            //记录推送的数据
            result.put("code", Constants.SUCCESS_200);
            System.out.println(json);
            System.out.println(json.getString("msgid"));
            redisService4.setString(json.getString("msgid"), data.toJSONString(),1800L);
        }else{
            result.put("msg", json.getString("errmsg"));
            result.put("code", Constants.Fail_400);
        }
        return  result;
    }

    /**
     * 转化成时间字符串格式
     * @param date
     * @return
     * @throws Exception
     */
    public static String getTimeString(Object date,String pattern)throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * 去掉json中的空字符串值
     * @return
     */
    public static JSONObject jsonTrim(JSONObject json) throws Exception{
        Set<String> set = json.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()){
            String key = it.next();
            Object val = json.get(key);
            if(null==val){
                continue;
            }
            if(val.toString().trim().equals("")){
                json.put(key, null);
            }
        }
        return json;
    }


    public static void main(String[] args) {
        try {
            Object o = "";
            System.out.println(o.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
